import {getToken,setToken,removeToken,setTimestamp} from '@/utils/auth'
import {login,getUserInfo,getUserDatebyId} from '@/api/user'

//状态
const state={
  token:getToken(),/*这是token为共享，初始化vuex的时候就先去缓存中读取token*/
  userinfo:{}
}
//修改状态
const mutations={

  SetToken(state,token){
    state.token=token
    setToken(token)
  },

 RemoveToken(state){
    state.token=null
    removeToken()
  },

  setUserInfo(state,info){
    state.userinfo=info
  },
  removeUserinfo(state){
    state.userinfo={}
  }
}
//异步方法
const actions={
 //登录方法
 async login(context,data){
    const resoult=await login(data)//这里的login是引入进来的api 的login
   context.commit('SetToken',resoult)// 提交mutations设置token
   setTimestamp() //设置时间戳

  },
  //登出
  logout(context){
   context.commit('RemoveToken')
    context.commit('removeUserinfo')
  },
//  获取用户信息
  async getUserInfo(context){
    const resoult=await getUserInfo()
    const baseInfo=await getUserDatebyId(resoult.userId)
    const obj={...resoult,...baseInfo}
    context.commit('setUserInfo',obj)
    return resoult

  }


}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}






